﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DFGK_WMS.WebAPI
{
    public class OverallException : IAsyncExceptionFilter
    {
        private readonly ILogger<OverallException> logger;
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="logger"></param>
        public OverallException(ILogger<OverallException> logger)
        {
            this.logger = logger;
        }

        /// <summary>
        /// 全局异常过滤器
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                //还没处理的异常进来
                var request = context.HttpContext.Request;
                var url = request.Path;
                //var queryParams = request.QueryString.ToString();
                //记录日志
                ApiResult result = new ApiResult();
                result.code = "500";
                result.message = "全局异常：" + context.Exception.Message;
                result.data = false;
                result.count = 0;
                context.Result = new JsonResult(result);

                logger.LogError($"接口地址:{url},信息:{result.message}");
                context.ExceptionHandled = true;  //标注下当前这个异常已经处理过了
            }
            return Task.CompletedTask;
        }
    }
}
